#various scripts and tools
DEFAULT_HOST_URL = u"http://localhost:5000"

from plonetheme.apkntheme import logger
from urlparse import urlparse
from httplib import HTTP, CannotSendHeader, CannotSendRequest
from socket import gaierror, timeout
import hashlib
import string
from random import randrange

from plone.memoize import ram

def generate_random_string(LENGTH_OF_STRING = 10):
    letter_len = len(string.lowercase)
    return ''.join([string.lowercase[randrange(letter_len)] \
    for x in xrange(LENGTH_OF_STRING)])

def cache_key_simple(func, var):
    return hashlib.md5(var).hexdigest()

def get_host_url(request):
    host_url = DEFAULT_HOST_URL
    try:
        host_url = request.get('VIRTUAL_URL_PARTS', ('',))[0]
    except:
        logger.error("Failed to extract host url from request: %s", request.__str())
    return host_url


def add_params_to_url(url, dict_params):
    import urllib
    import urlparse
    
    url_parts = list(urlparse.urlparse(url))
    url_query = url_parts[4]
    if not len(url_query):
        url_query = urllib.urlencode(dict_params)    
    else:
        url_query += "&%s" %(urllib.urlencode(dict_params))
    url_parts[4] = url_query

    return urlparse.urlunparse(tuple(url_parts))

@ram.cache(cache_key_simple)
def checkURLExists(url = None):
    """
    Accepts an http address and checks its existence
    >>> checkURLExists("")
    False
    >>> checkURLExists()
    False
    >>> checkURLExists(1)
    False
    >>> checkURLExists({})
    False
    >>> checkURLExists("google")
    False
    >>> checkURLExists("google.com")
    False
    >>> checkURLExists("www.google.com")
    False
    >>> checkURLExists("http://www.google.com/")
    True
    >>> checkURLExists("http://www.google.com/search")
    True
    >>> checkURLExists("http://797750jf-aifp-27012.google.com/")
    False
    #This should return False if no dns interceptor exists
    """
    urlexists = False
    
    if isinstance(url, str) or isinstance(url, unicode):
        if url:
            parsed = urlparse(url, scheme="http")
            
            http_req = HTTP(parsed[1])
            try:
                http_req.putrequest('HEAD', parsed[2])
                http_req.endheaders()
                if http_req.getreply()[0] < 400:
                    urlexists = True
            except (CannotSendHeader, 
                    CannotSendRequest, 
                    gaierror, 
                    timeout):
                pass
     
    return urlexists
